using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;
using MediPlatform.Read.Api.Services;

namespace MediPlatform.Read.Api.Services
{
    public class PrescriptionOrderDataInitializer
    {
        private readonly MyDbContext _context;
        private readonly ILogger<PrescriptionOrderDataInitializer> _logger;

        public PrescriptionOrderDataInitializer(MyDbContext context, ILogger<PrescriptionOrderDataInitializer> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task InitializeAsync()
        {
            try
            {
                _logger.LogInformation("开始初始化处方流转订单测试数据");

                // 检查是否已有数据
                if (await _context.PrescriptionOrder.AnyAsync())
                {
                    _logger.LogInformation("处方流转订单数据已存在，跳过初始化");
                    return;
                }

                // 确保有用户数据
                await EnsureUsersExistAsync();

                // 确保有处方数据
                await EnsurePrescriptionsExistAsync();

                // 创建处方流转订单
                await CreatePrescriptionOrdersAsync();

                // 创建处方流转日志
                await CreatePrescriptionLogsAsync();

                await _context.SaveChangesAsync();

                _logger.LogInformation("处方流转订单测试数据初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化处方流转订单测试数据失败");
                throw;
            }
        }

        private async Task EnsureUsersExistAsync()
        {
            // 检查是否有足够的患者用户
            var patientCount = await _context.User.Where(u => u.Role == "patient").CountAsync();
            var doctorCount = await _context.User.Where(u => u.Role == "doctor").CountAsync();

            if (patientCount < 3 || doctorCount < 3)
            {
                var users = new List<User>();

                // 如果患者不足，添加患者
                if (patientCount < 3)
                {
                    for (int i = patientCount; i < 3; i++)
                    {
                        users.Add(new User 
                        { 
                            UserId = $"P{(i + 1):D3}", 
                            Username = $"患者{i + 1}", 
                            PhoneNumber = $"1380013800{i + 1}", 
                            PasswordHash = "hashed_password", 
                            Role = "patient" 
                        });
                    }
                }

                // 如果医生不足，添加医生
                if (doctorCount < 3)
                {
                    for (int i = doctorCount; i < 3; i++)
                    {
                        users.Add(new User 
                        { 
                            UserId = $"D{(i + 1):D3}", 
                            Username = $"医生{i + 1}", 
                            PhoneNumber = $"1390013900{i + 1}", 
                            PasswordHash = "hashed_password", 
                            Role = "doctor" 
                        });
                    }
                }

                if (users.Any())
                {
                    _context.User.AddRange(users);
                    await _context.SaveChangesAsync();
                    _logger.LogInformation("已添加 {Count} 个用户", users.Count);
                }
            }
        }

        private async Task EnsurePrescriptionsExistAsync()
        {
            if (!await _context.Prescription.AnyAsync())
            {
                var patients = await _context.User.Where(u => u.Role == "patient").ToListAsync();
                var doctors = await _context.User.Where(u => u.Role == "doctor").ToListAsync();

                // 检查是否有足够的用户数据
                if (patients.Count < 3 || doctors.Count < 3)
                {
                    _logger.LogWarning("用户数据不足，无法创建处方数据。需要至少3个患者和3个医生。");
                    return;
                }

                var prescriptions = new List<Prescription>
                {
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101001",
                        PatientId = patients[0].Id,
                        DoctorId = doctors[0].Id,
                        HospitalId = 1,
                        DepartmentId = 1,
                        Diagnosis = "感冒",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-5)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101002",
                        PatientId = patients[1].Id,
                        DoctorId = doctors[1].Id,
                        HospitalId = 1,
                        DepartmentId = 2,
                        Diagnosis = "高血压",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-4)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101003",
                        PatientId = patients[2].Id,
                        DoctorId = doctors[2].Id,
                        HospitalId = 2,
                        DepartmentId = 3,
                        Diagnosis = "糖尿病",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-3)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101004",
                        PatientId = patients[0].Id,
                        DoctorId = doctors[0].Id,
                        HospitalId = 1,
                        DepartmentId = 1,
                        Diagnosis = "胃炎",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-2)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101005",
                        PatientId = patients[1].Id,
                        DoctorId = doctors[1].Id,
                        HospitalId = 2,
                        DepartmentId = 4,
                        Diagnosis = "妇科炎症",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-1)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101006",
                        PatientId = patients[2].Id,
                        DoctorId = doctors[2].Id,
                        HospitalId = 1,
                        DepartmentId = 5,
                        Diagnosis = "支气管炎",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-6)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101007",
                        PatientId = patients[0].Id,
                        DoctorId = doctors[1].Id,
                        HospitalId = 2,
                        DepartmentId = 6,
                        Diagnosis = "关节炎",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-7)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101008",
                        PatientId = patients[1].Id,
                        DoctorId = doctors[2].Id,
                        HospitalId = 1,
                        DepartmentId = 7,
                        Diagnosis = "失眠",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-8)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101009",
                        PatientId = patients[2].Id,
                        DoctorId = doctors[0].Id,
                        HospitalId = 2,
                        DepartmentId = 8,
                        Diagnosis = "皮肤病",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-9)
                    },
                    new Prescription
                    {
                        PrescriptionNo = "RX20250101010",
                        PatientId = patients[0].Id,
                        DoctorId = doctors[1].Id,
                        HospitalId = 1,
                        DepartmentId = 9,
                        Diagnosis = "心脏病",
                        Status = 1,
                        ValidUntil = DateTime.Now.AddDays(7),
                        CreatedAt = DateTime.Now.AddDays(-10)
                    }
                };

                _context.Prescription.AddRange(prescriptions);
                await _context.SaveChangesAsync();
            }
        }

        private async Task CreatePrescriptionOrdersAsync()
        {
            var patients = await _context.User.Where(u => u.Role == "patient").ToListAsync();
            var doctors = await _context.User.Where(u => u.Role == "doctor").ToListAsync();
            var prescriptions = await _context.Prescription.ToListAsync();

            // 检查是否有足够的数据
            if (patients.Count < 3 || doctors.Count < 3 || prescriptions.Count < 10)
            {
                _logger.LogWarning("数据不足，无法创建处方流转订单。需要至少3个患者、3个医生和10个处方。");
                return;
            }

            var orders = new List<PrescriptionOrder>
            {
                // 待支付订单
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101001",
                    PrescriptionId = prescriptions[0].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 200,
                    DiscountAmount = 20,
                    CreatedAt = DateTime.Now.AddDays(-5)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101002",
                    PrescriptionId = prescriptions[1].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 350,
                    DiscountAmount = 30,
                    CreatedAt = DateTime.Now.AddDays(-4)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101003",
                    PrescriptionId = prescriptions[2].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 1,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 180,
                    DiscountAmount = 15,
                    CreatedAt = DateTime.Now.AddDays(-3)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101004",
                    PrescriptionId = prescriptions[3].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 3,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 450,
                    DiscountAmount = 45,
                    CreatedAt = DateTime.Now.AddDays(-2)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101005",
                    PrescriptionId = prescriptions[4].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 2,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 320,
                    DiscountAmount = 32,
                    CreatedAt = DateTime.Now.AddDays(-1)
                },

                // 已完成订单
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101006",
                    PrescriptionId = prescriptions[0].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 280,
                    DiscountAmount = 25,
                    PaymentMethod = "wechat",
                    PaymentTime = DateTime.Now.AddDays(-10),
                    DeliveryAddress = "北京市朝阳区建国路88号",
                    LogisticsCompany = "顺丰快递",
                    TrackingNumber = "SF1234567890",
                    SignTime = DateTime.Now.AddDays(-8),
                    CreatedAt = DateTime.Now.AddDays(-10)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101007",
                    PrescriptionId = prescriptions[1].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 420,
                    DiscountAmount = 40,
                    PaymentMethod = "alipay",
                    PaymentTime = DateTime.Now.AddDays(-9),
                    DeliveryAddress = "上海市浦东新区陆家嘴金融中心",
                    LogisticsCompany = "圆通快递",
                    TrackingNumber = "YT9876543210",
                    SignTime = DateTime.Now.AddDays(-7),
                    CreatedAt = DateTime.Now.AddDays(-9)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101008",
                    PrescriptionId = prescriptions[2].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 3,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 380,
                    DiscountAmount = 35,
                    PaymentMethod = "bank_card",
                    PaymentTime = DateTime.Now.AddDays(-8),
                    DeliveryAddress = "广州市天河区珠江新城",
                    LogisticsCompany = "中通快递",
                    TrackingNumber = "ZT5678901234",
                    SignTime = DateTime.Now.AddDays(-6),
                    CreatedAt = DateTime.Now.AddDays(-8)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101009",
                    PrescriptionId = prescriptions[3].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 520,
                    DiscountAmount = 50,
                    PaymentMethod = "wechat",
                    PaymentTime = DateTime.Now.AddDays(-7),
                    DeliveryAddress = "深圳市南山区科技园",
                    LogisticsCompany = "申通快递",
                    TrackingNumber = "ST2345678901",
                    SignTime = DateTime.Now.AddDays(-5),
                    CreatedAt = DateTime.Now.AddDays(-7)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101010",
                    PrescriptionId = prescriptions[4].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 290,
                    DiscountAmount = 28,
                    PaymentMethod = "alipay",
                    PaymentTime = DateTime.Now.AddDays(-6),
                    DeliveryAddress = "杭州市西湖区文三路",
                    LogisticsCompany = "韵达快递",
                    TrackingNumber = "YD3456789012",
                    SignTime = DateTime.Now.AddDays(-4),
                    CreatedAt = DateTime.Now.AddDays(-6)
                },

                // 已失效订单
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101011",
                    PrescriptionId = prescriptions[0].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 3,
                    Status = 7,
                    PaymentStatus = 0,
                    PaymentAmount = 150,
                    DiscountAmount = 10,
                    CancelReason = "患者取消订单",
                    CreatedAt = DateTime.Now.AddDays(-12)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101012",
                    PrescriptionId = prescriptions[1].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 3,
                    PaymentStatus = 2,
                    PaymentAmount = 300,
                    DiscountAmount = 25,
                    PaymentMethod = "bank_card",
                    PaymentTime = DateTime.Now.AddDays(-15),
                    RefundAmount = 300,
                    RefundTime = DateTime.Now.AddDays(-14),
                    CancelReason = "药品缺货，申请退款",
                    CreatedAt = DateTime.Now.AddDays(-15)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101013",
                    PrescriptionId = prescriptions[2].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 7,
                    PaymentStatus = 0,
                    PaymentAmount = 220,
                    DiscountAmount = 20,
                    CancelReason = "患者临时有事，取消订单",
                    CreatedAt = DateTime.Now.AddDays(-11)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101014",
                    PrescriptionId = prescriptions[3].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 3,
                    Status = 3,
                    PaymentStatus = 2,
                    PaymentAmount = 480,
                    DiscountAmount = 45,
                    PaymentMethod = "wechat",
                    PaymentTime = DateTime.Now.AddDays(-13),
                    RefundAmount = 480,
                    RefundTime = DateTime.Now.AddDays(-12),
                    CancelReason = "处方信息有误，需要重新开具",
                    CreatedAt = DateTime.Now.AddDays(-13)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101015",
                    PrescriptionId = prescriptions[4].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 7,
                    PaymentStatus = 0,
                    PaymentAmount = 180,
                    DiscountAmount = 15,
                    CancelReason = "患者选择其他药店",
                    CreatedAt = DateTime.Now.AddDays(-10)
                },

                // 更多待支付订单
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101016",
                    PrescriptionId = prescriptions[5].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 1,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 260,
                    DiscountAmount = 25,
                    CreatedAt = DateTime.Now.AddDays(-2)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101017",
                    PrescriptionId = prescriptions[6].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 390,
                    DiscountAmount = 35,
                    CreatedAt = DateTime.Now.AddDays(-1)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101018",
                    PrescriptionId = prescriptions[7].Id,
                    PatientId = patients[1].Id,
                    DoctorId = doctors[2].Id,
                    PharmacyId = 3,
                    Status = 0,
                    PaymentStatus = 0,
                    PaymentAmount = 180,
                    DiscountAmount = 18,
                    CreatedAt = DateTime.Now.AddDays(-1)
                },

                // 更多已完成订单
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101019",
                    PrescriptionId = prescriptions[8].Id,
                    PatientId = patients[2].Id,
                    DoctorId = doctors[0].Id,
                    PharmacyId = 1,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 340,
                    DiscountAmount = 30,
                    PaymentMethod = "alipay",
                    PaymentTime = DateTime.Now.AddDays(-5),
                    DeliveryAddress = "成都市锦江区春熙路",
                    LogisticsCompany = "百世快递",
                    TrackingNumber = "BS4567890123",
                    SignTime = DateTime.Now.AddDays(-3),
                    CreatedAt = DateTime.Now.AddDays(-5)
                },
                new PrescriptionOrder
                {
                    OrderNo = "PO20250101020",
                    PrescriptionId = prescriptions[9].Id,
                    PatientId = patients[0].Id,
                    DoctorId = doctors[1].Id,
                    PharmacyId = 2,
                    Status = 6,
                    PaymentStatus = 1,
                    PaymentAmount = 580,
                    DiscountAmount = 55,
                    PaymentMethod = "wechat",
                    PaymentTime = DateTime.Now.AddDays(-4),
                    DeliveryAddress = "武汉市江汉区解放大道",
                    LogisticsCompany = "德邦快递",
                    TrackingNumber = "DB5678901234",
                    SignTime = DateTime.Now.AddDays(-2),
                    CreatedAt = DateTime.Now.AddDays(-4)
                }
            };

            _context.PrescriptionOrder.AddRange(orders);
            await _context.SaveChangesAsync();
        }

        private async Task CreatePrescriptionLogsAsync()
        {
            var orders = await _context.PrescriptionOrder.ToListAsync();

            var logs = new List<PrescriptionLog>();

            foreach (var order in orders)
            {
                // 为每个订单创建流转日志
                var orderLogs = new List<PrescriptionLog>();

                // 初始状态
                orderLogs.Add(new PrescriptionLog
                {
                    OrderId = order.Id,
                    Status = order.Status,
                    OperatorId = 1,
                    OperateTime = order.CreatedAt,
                    Remark = "订单创建"
                });

                // 根据订单状态添加相应的日志
                if (order.Status >= 1)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 1,
                        OperatorId = 1,
                        OperateTime = order.CreatedAt.Value.AddMinutes(5),
                        Remark = "处方已发送到药店"
                    });
                }

                if (order.Status >= 2)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 2,
                        OperatorId = 2,
                        OperateTime = order.CreatedAt.Value.AddMinutes(10),
                        Remark = "药店已接收处方"
                    });
                }

                if (order.Status >= 3)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 3,
                        OperatorId = 2,
                        OperateTime = order.CreatedAt.Value.AddMinutes(15),
                        Remark = "药店已审核处方"
                    });
                }

                if (order.Status >= 4)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 4,
                        OperatorId = 2,
                        OperateTime = order.CreatedAt.Value.AddMinutes(30),
                        Remark = "已配药完成"
                    });
                }

                if (order.Status >= 5)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 5,
                        OperatorId = 2,
                        OperateTime = order.CreatedAt.Value.AddHours(1),
                        Remark = "患者已取药"
                    });
                }

                if (order.Status >= 6)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 6,
                        OperatorId = 3,
                        OperateTime = order.SignTime ?? order.CreatedAt.Value.AddDays(1),
                        Remark = "配送完成，已签收"
                    });
                }

                if (order.Status == 7)
                {
                    orderLogs.Add(new PrescriptionLog
                    {
                        OrderId = order.Id,
                        Status = 7,
                        OperatorId = 1,
                        OperateTime = order.CreatedAt.Value.AddHours(2),
                        Remark = order.CancelReason ?? "订单已取消"
                    });
                }

                logs.AddRange(orderLogs);
            }

            _context.PrescriptionLog.AddRange(logs);
            await _context.SaveChangesAsync();
        }
    }
} 